<?php
/**
 * Nordic Repository
 * 
 * LICENSE
 * 
 * The new BSD license is applied on this source-file. For further
 * information please visit http://license.nordic-dev.de/newbsd.txt
 * or send an email to andre.moelle@gmail.com.
 */

/**
 * This schema-class is used for encoding and decoding data of ini
 * files.
 * 
 * @category   Nordic
 * @package    Nordic_Schema
 * @copyright  2007 Nordic Development
 * @license    http://license.nordic-dev.de/newbsd.txt (New-BSD license)
 * @author     Andre Moelle <andre.moelle@gmail.com>
 * @version    $Id: Ini.php 3 2007-07-08 09:21:42Z andre.moelle $
 */
class Nordic_Schema_Ini implements Nordic_Schema_Interface
{
	/**
	 * 
	 * 
	 * @access private
	 * @param Array $array array to convert
	 * @param Integer $dim dimension of the array
	 * @param String $name key of the element
	 */
	function _convertArray ($array, $dim = 0, $name = '')
	{
		$vRetVal = '';
		$vTmpVal = '';
		
		if(!is_array($array) || count($array) == 0)
			return '';
		
		foreach($array as $co => $val)		
		{
			if($dim == 0)
				$vRetVal .= "[" . $co . "]\n";
			else if($dim == 1)
				$vTmpVal = $co;
			else
				$vTmpVal = $name . '.' . $co;

			if(is_array($val))
			{
				$vRetVal .= 
					$this->_convertArray($val, $dim + 1, $vTmpVal);
			}
			else if($dim > 0)
			{
				$vRetVal .= $vTmpVal . " = \"" . $val . "\"\n";
			}
		}

		return $vRetVal;
	}
	/**
	 * @see Nordic_Schema_Interface::decode()
	 */
	public function decode ($array)
	{
		return $this->_convertArray($array);
	}
	
	/**
	 * @see Nordic_Schema_Interface::encode()
	 */
	public function encode ($string)
	{
		$retArray = array();
		$groupAct = '';
		$varArray = array();
		$vEval = '';	
		
		foreach(explode("\n", $string) as $data)
		{
			$data = trim($data);
			
			$CFirst = strpos($data, '[');
			$CLast = strrpos($data, ']');
			
			if($CFirst === false || $CLast === false)
			{
				$ESign = strpos($data, '=');
				
				$Value = substr($data, $ESign + 1, strlen($data));
				$Var = substr($data, 0, $ESign - 1);
				
				$Value = trim($Value);
				$Value = trim($Value, '"');

				$Var = trim($Var);
				$Var = trim($Var, '"');
				
				$varArray = explode('.', $Var);
				
				$vTEval = "";
				
				foreach($varArray as $co => $val)
					$vTEval .= '["' . $val . '"]';
				
				$vEval .= '$retArray["' . $groupAct . '"]'
					. $vTEval . '= "' . $Value . '";';
			
			}
			else
			{
				$groupAct = substr($data, $CFirst+1, $CLast-1);
				$retArray[$groupAct] = array();
			}
		}
		
		eval($vEval);
		
		foreach($retArray as $co => $val)
		{
			if($val == null)
				unset($retArray[$co]);
		}
		
		return $retArray;
	}
}
?>